<?php
namespace app\api\controller;
use think\Exception;
use think\Request;
use think\db;
use app\base\model\Order as OrderModel;
use app\base\model\OrderGoods;
use app\base\model\GoodsComment;
use app\base\model\CommentImages;
use app\base\model\Cart;
use app\base\model\Goods;
use app\base\model\ReceiveAddress;
use app\base\model\Area;
use app\base\model\GoodsAttrCombination;
use app\base\model\Attribute;
use app\base\model\AttributeValues;
use app\base\model\UserCoupon;
use app\base\model\Coupons;
class Order extends Base{
    //订单模型
    protected $order;
    //订单商品模型
    protected $orderGoods;
    //商品评论模型
    protected $comment;
    //商品评论图片模型
    protected $comment_image;
    //购物车模型
    protected $cart;
    //商品模型
    protected $goods;
    //优惠券模型
    protected $coupons;
    //用户优惠券模型
    protected $user_coupons;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->order = new OrderModel();
        $this->orderGoods=new OrderGoods();
        $this->comment = new GoodsComment();
        $this->comment_image = new CommentImages();
        $this->cart  = new Cart();
        $this->goods = new Goods();
        $this->coupons=new Coupons();
        $this->user_coupons=new UserCoupon();
    }
    /**
     *用户的订单列表
     * return json
     */
    public function ordersList(){
       if(empty($this->userInfo)){
           return $msg['message']=checkMsg(LOGIN_ERROR);
       }
       $status  = $this->request->post('status',0); //0:全部订单 1:待支付 2:待发货 3:待收货 4:待评价 5:已完成
       $pageNo  = $this->request->post('pageNo',1);
       $pageSize= $this->request->post('pageSize',10);
       $result=$this->order->getOrderList($this->user_id,$status,$pageNo,$pageSize);
      if(empty($result['list'])){
          $msg['message']=checkMsg(GET_DATA_FAILE);
      }else{
          $msg['message']=checkMsg(GET_DATA_SUCCESS);
      }
      $msg['list']=$result['list'];
      $msg['total']=$result['total'];
      return  $msg;
    }
    /**
     * 确认订单信息
     *return json
     */
    public function confirmOrders(){
        if(empty($this->userInfo)){
            $msg['message']=checkMsg(LOGIN_ERROR);
            return $msg;
        }
        $cart_ids = $this->request->post('cart_ids/a',[]);
        $goods_id = $this->request->post('goods_id',0);
        if(empty($cart_ids) && empty($goods_id)){
            $msg['message']=checkMsg(CANSHU_ERROR);
            return $msg;
        }
        $goods_total_amount=0.00;
        $goods_total_num=0;
        $attr_model = new Attribute();
        $attr_value_model = new AttributeValues();
        $goods_attr_com = new GoodsAttrCombination();
        if(!empty($cart_ids)){
            $goods_list=$this->cart->alias('c')
                                   ->join('yc_goods g','g.goods_id=c.goods_id','left')
                                   ->join('yc_goods_attr_combination gac','gac.com_id=c.com_id','left')
                                   ->where(['c.cart_id'=>['in',$cart_ids],'c.user_id'=>$this->user_id])
                                   ->field('c.cart_id,c.user_id,c.com_id,c.goods_num,c.goods_price,c.goods_total_price,g.goods_name,g.goods_thumb,g.goods_desc,gac.values_id')
                                   ->order('c.cart_id','desc')
                                   ->select();
             foreach($goods_list as $key=>$value){
                    $goods_total_amount+=$value['goods_total_price'];
                   $goods_total_num+=$value['goods_num'];
                    $attr_val_arr=explode(',',$value['values_id']);
                    $attr=[];
                    for($i=0;$i<count($attr_val_arr);$i++){
                        $val_info=$attr_value_model->where(['id'=>$attr_val_arr[$i]])->find();
                        $attr_info =$attr_model->where(['attr_id'=>$val_info['attr_id']])->find();
                         $attr[$attr_info['attr_name']]=$val_info['value'];
                    }
                    $goods_list[$key]['goods_attr']=$attr;
             }
        }else{
            $com_id = $this->request->post('com_id');
            $goods_total_num =$this->request->post('goods_num',1);
            $goods_info=$this->goods->where(['goods_id'=>$goods_id])->field('goods_name,goods_price,goods_thumb,goods_desc')->find();
            $com_info=$goods_attr_com->where(['goods_id'=>$goods_id,'com_id'=>$com_id])->find();
            if(!empty($com_info)){
                $goods_price=$com_info['price'];
                $goods_total_amount=$goods_price*$goods_total_num;
                $attr_val_arr=explode(',',$com_info['values_id']);
                $attr=[];
                for($i=0;$i<count($attr_val_arr);$i++){
                    $val_info=$attr_value_model->where(['id'=>$attr_val_arr[$i]])->find();
                    $attr_info =$attr_model->where(['attr_id'=>$val_info['attr_id']])->find();
                    $attr[$attr_info['attr_name']]=$val_info['value'];
                }
                $goods_info['goods_price']=$goods_price;
                $goods_info['goods_attr']=$attr;
            }else{
                $goods_info=$this->goods->where(['goods_id'=>$goods_id])->field('goods_name,goods_price,goods_thumb,goods_desc')->find();
                $goods_price=$goods_info['goods_price'];
                $goods_total_amount=$goods_price*$goods_total_num;
                $goods_info['goods_attr']=[];
            }
            $goods_list[0]=$goods_info;
        }
        $date_time=date('Y.m.d',time());
        $coupon_list=$this->coupons->alias('c')
                                   ->join('yc_user_coupon uc','uc.cid=c.c_id','left')
                                    ->where(['c.cond_amount'=>['<=',$goods_total_amount],'c.start_time'=>['<=',$date_time],'c.end_time'=>['>=',$date_time],'uc.status'=>1,'uc.uid'=>$this->user_id])
                                    ->field('c.c_id,c.amount')
                                    ->select();
        $msg['message']=checkMsg(GET_DATA_SUCCESS);
        $msg['goods_list']=$goods_list;
        $msg['goods_total_num']=$goods_total_num;
        $msg['goods_total_amount']=$goods_total_amount;
        $msg['coupon_list']=$coupon_list;
        $msg['goods_id']=$goods_id;
        $msg['cart_ids']=$cart_ids;
        return $msg;
    }
    /**
     *使用优惠券
     * return json
     */
    public function useCoupons(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $c_id = $this->request->post('c_id');
      $total_amount=$this->request->post('total_amount');
      if(empty($c_id) ||empty($total_amount)){
          $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $couponsInfo=$this->coupons->where(['c_id'=>$c_id])->find();
      $cope_amount=$total_amount-$couponsInfo['amount'];
      $msg['message']=checkMsg(OPERA_SUCCESS);
      $msg['coupons_amount']=$couponsInfo['amount'];
      $msg['cope_amount']=$cope_amount;
      return $msg;
    }
    /**
     *创建订单
     * return json
     */
    public function createOrder(){
        if(empty($this->userInfo)){
            $msg['message']=checkMsg(LOGIN_ERROR);
            return $msg;
        }
        $cart_ids = $this->request->post('cart_ids/a',[]);
        $goods_id = $this->request->post('goods_id');
        $address_id = $this->request->post('address_id');
        if(empty($address_id)){
            $msg['message']=checkMsg(CHOSE_ADDRESS);
            return $msg;
        }
        $addressModel = new ReceiveAddress();
        $addressInfo = $addressModel->where(['id'=>$address_id,'is_delete'=>0])->find();
        if(empty($addressInfo)){
            $msg['message']=checkMsg(RECEIVE_ADDRESS_NOT_EXITS);
            return $msg;
        }
        if(empty($cart_ids) && empty($goods_id)){
            $msg['message']=checkMsg(CANSHU_ERROR);
            return $msg;
        }
        $coupons_id=$this->request->post('coupons_id');
        if(!empty($coupons_id)){
            $coupons = new Coupon();
            $cInfo=$coupons->where(['c_id'=>$coupons_id])->find();
            $c_amount=$cInfo['amount'];
        }else{
            $c_amount=0.00;
        }
        $order_sn=$str = date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        if(!empty($cart_ids)){  //从购物车中创建菜单
            $total_amount=0.00;
            $goods_total_num=0;
           for($i=0;$i<count($cart_ids);$i++){
             $cartInfo=$this->cart->where(['cart_id'=>$cart_ids[$i]])->find();
             $total_amount+=$cartInfo['goods_total_price'];
             $goods_total_num+=$cartInfo['goods_num'];
           }
          $order_data=[
              'order_sn'  =>$order_sn,
              'user_id'   =>$this->user_id,
              'order_status'=>1,
              'goods_total_num' =>$goods_total_num,
              'order_total_amount'=>$total_amount,
              'order_pay_amount'  =>$total_amount-$c_amount,
              'coupons'           =>$c_amount,
              'receiver'          =>$addressInfo['user_name'],
              'phone'             =>$addressInfo['phone'],
              'province'         =>$addressInfo['province'],
              'city'              =>$addressInfo['city'],
              'district'          =>$addressInfo['district'],
              'address'           =>$addressInfo['address'],
              'add_time'        =>time()
          ];
           $order_id=$this->order->insertGetId($order_data);
           if($order_id){
               $order_goods=[];
               for($i=0;$i<count($cart_ids);$i++){
                   $cartInfo=$this->cart->where(['cart_id'=>$cart_ids[$i]])->find();
                   $order_goods_data=[
                       'order_id'  =>$order_id,
                       'user_id'   =>$this->user_id,
                       'goods_id'  =>$cartInfo['goods_id'],
                       'goods_num' =>$cartInfo['goods_num'],
                       'goods_attr_com_id' =>$cartInfo['com_id'],
                       'goods_price'      => $cartInfo['goods_price'],
                       'goods_amount'    => $cartInfo['goods_total_price'],
                       'add_time'       =>time()
                   ];
                   array_push($order_goods,$order_goods_data);
               }
               $this->orderGoods->insertAll($order_goods);
               $this->cart->where(['cart_id'=>['in',$cart_ids]])->delete();
               $msg['message']=checkMsg(CREATE_ORDER_SUCCESS);
           }else{
               $msg['message']=checkMsg(CREATE_ORDER_FAIL);
           }
        }else{  //立即购买
            $com_id = $this->request->post('com_id');
            $goods_num =$this->request->post('goods_num',1);
            $goods_attr_com=new GoodsAttrCombination();
            $com_info=$goods_attr_com->where(['goods_id'=>$goods_id,'com_id'=>$com_id])->find();
            if(!empty($com_info)){
                $goods_price=$com_info['price'];
                $goods_amount=$goods_price*$goods_num;
            }else{
                $goodsInfo=$this->goods->where(['goods_id'=>$goods_id])->find();
                $goods_price=$goodsInfo['goods_price'];
                $goods_amount=$goods_price*$goods_num;
            }
            $order_data=[
                'user_id'  =>$this->user_id,
                'order_sn'   =>$order_sn,
                'goods_total_num' =>$goods_num,
                'order_total_amount' =>$goods_amount,
                'order_pay_amount'   =>$goods_amount-$c_amount,
                'coupons'            =>$c_amount,
                'receiver'          =>$addressInfo['user_name'],
                'phone'             =>$addressInfo['phone'],
                'province'         =>$addressInfo['province'],
                'city'              =>$addressInfo['city'],
                'district'          =>$addressInfo['district'],
                'address'           =>$addressInfo['address'],
                'add_time'        =>time()
            ];
          $order_id=$this->order->insertGetId($order_data);
          if($order_id){
              $order_goods_data=[
                  'order_id'  => $order_id,
                  'user_id'   =>$this->user_id,
                  'goods_id'  =>$goods_id,
                  'goods_num' =>$goods_num,
                  'goods_attr_com_id'=>$com_id,
                  'goods_price'    =>$goods_price,
                  'goods_amount'   =>$goods_amount,
                  'add_time'       =>time()
              ];
              $this->orderGoods->insertGetId($order_goods_data);
              $msg['message']=checkMsg(CREATE_ORDER_SUCCESS);
          }else{
              $msg['message']=checkMsg(CREATE_ORDER_FAIL);
          }
        }
       return $msg;
    }
    /**
     *订单详情
     *return json
     */
    public function ordersDetail(){
        if(empty($this->userInfo)){
            $msg['message']=checkMsg(LOGIN_ERROR);
            return $msg;
        }
        $order_id=$this->request->post('order_id');
        if(empty($order_id)){
             $msg['message']=checkMsg(CANSHU_ERROR);
             return $msg;
        }
        $where=[
            'user_id'  =>$this->user_id,
            'order_id' =>$order_id,
            'is_delete'=>0
        ];
        $count=$this->order->where($where)->count();
        if($count<0){
            return $msg['message']=checkMsg(ORDER_NOT_EXIT);
        }
       $orderInfo=$this->order->getOrderInfo($this->user_id,$order_id);
        if(empty($orderInfo)){
            return $msg['message']=checkMsg(GET_DATA_FAILE);
        }else{
            $msg['message']=checkMsg(GET_DATA_SUCCESS);
            $msg['info']=$orderInfo;
            return $msg;
        }
    }
   /**
    *取消或删除订单
    * return json
    */
    public function cancelOrDelete(){
        if(empty($this->userInfo)){
            $msg['message']=checkMsg(LOGIN_ERROR);
            return $msg;
        }
        $order_id = $this->request->post('order_id');
        $type     = $this->request->post('type','1'); //1:取消订单 2:删除订单
        if(empty($order_id)){
            $msg['message']=checkMsg(CANSHU_ERROR);
            return $msg;
        }
        $where=[
            'user_id' =>$this->user_id,
            'order_id' =>$order_id,
            'is_delete' =>0
        ];
        $count=$this->order->where($where)->count();
        if($count<1){
           $msg['message']=checkMsg(ORDER_NOT_EXIT);
           return $msg;
        }
        if($type==1){  //取消订单
            $res=$this->order->save(['order_status'=>6],$where);
        }else{  //删除订单
            $res=$this->order->save(['is_delete'=>1],$where);
        }
        if($res){
            $msg['message']=checkMsg(UPDATE_DATA_SUCCESS);
        }else{
            $msg['message']=checkMsg(UPDATE_DATA_FAIL);
        }
        return $msg;
    }
  /**
   *确认收货
   * return json
   */
    public function confirmOrder(){
        if(empty($this->userInfo)){
            $msg['message']=checkMsg(LOGIN_ERROR);
            return $msg;
        }
        $order_id = $this->request->post('order_id');
        if(empty($order_id)){
            $msg['message']=checkMsg(CANSHU_ERROR);
            return $msg;
        }
        $where=[
            'user_id' =>$this->user_id,
            'order_id' =>$order_id,
            'order_status'=>3,
            'is_delete' =>0
        ];
        $count=$this->order->where($where)->count();
        if($count<1){
            $msg['message']=checkMsg(ORDER_NOT_EXIT);
            return $msg;
        }
        $res=$this->order->save(['order_status'=>1],$where);
        if($res){
            $msg['message']=checkMsg(UPDATE_DATA_SUCCESS);
        }else{
            $msg['message']=checkMsg(UPDATE_DATA_FAIL);
        }
        return $msg;
    }
   /**
    *搜索订单
    * return json
    */
  public function searchOrder(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $keywords=$this->request->post('keywords');
      $pageNo  =$this->request->post('pageNo','1');
      $pageSize=$this->request->post('pageSize',10);
      if(empty($keywords)){
          $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
     return  $result=$this->order->searchOrders($this->user_id,$keywords,$pageNo,$pageSize);
  }
  /**
   *添加商品评论
   * return json
   */
  public function addGoodsComment(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
     $goods_id = $this->request->post('goods_id');
     $order_id = $this->request->post('order_id');
     $images   = $this->request->post('images/a'); //评论图片
     $content  = $this->request->post('content');
     $star_num = $this->request->post('star_num');
     if(empty($goods_id) || empty($order_id) || empty($star_num)){
         $msg['message']=checkMsg(CANSHU_ERROR);
         return $msg;
     }
     $count = $this->comment->where(['user_id'=>$this->user_id,'goods_id'=>$goods_id,'order_id'=>$order_id])->count();
     if($count>0){
         $msg['message']=checkMsg(CONNOT_COMMENT_RE);
         return $msg;
     }
     $comment_data=[
         'user_id'  =>$this->user_id,
         'goods_id' =>$goods_id,
         'order_id' =>$order_id,
         'content'  =>$content,
         'star_num' =>$star_num,
         'add_time' =>time()
     ];
    $res=$this->comment->insertGetId($comment_data);
    if($res){
         if(!empty($images)){
             for($i=0;$i<count($images);$i++){
                 $image_data=[
                     'comment_id' =>$res,
                     'img_path'   =>$images[$i],
                     'add_time'   =>time()
                  ];
                 $this->comment_image->insertGetId($image_data);
             }
         }
         $this->order->where(['user_id'=>$this->user_id,'order_id'=>$order_id])->data(['order_status'=>5])->update();
        $msg['message']=checkMsg(COMMENT_SUCCESS);
    }else{
        $msg['message']=checkMsg(COMMENT_FAIL);
    }
    return $msg;
  }
  /**
   *订单评价
   * return json
   */
  public function commentOrders(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $order_id = $this->request->post('order_id');
      $comments = $this->request->post('comments/a');
      /*$comments=[
          [
              'goods_id' =>1,
              'star_num' =>3,
              'content'  =>'sdjafsgh',
              'images'   =>[
                  '/uploads/20190605/b4c6ee76b667d3a656ce9c61eea1a2d7.png',
                  '/uploads/20190605/b4c6ee76b667d3a656ce9c61eea1a2d7.png',
                  '/uploads/20190605/b4c6ee76b667d3a656ce9c61eea1a2d7.png',
              ]
          ],
          [
              'goods_id' =>3,
              'star_num' =>5,
              'content'  =>'sdjafsgh',
              'images'   =>[
                  '/uploads/20190605/b4c6ee76b667d3a656ce9c61eea1a2d7.png',
                  '/uploads/20190605/b4c6ee76b667d3a656ce9c61eea1a2d7.png',
                  '/uploads/20190605/b4c6ee76b667d3a656ce9c61eea1a2d7.png',
              ]
          ]
      ];*/
      if(empty($order_id)){
          $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $orderInfo = $this->order->where(['order_id'=>$order_id])->find();
     $this->comment->startTrans();
      try{
          foreach($comments as $key=>$value){
              if(empty($value['star_num'])){
                  $value['star_num']=5;
              }
              if(empty($value['content'])){
                  $value['content']='用户未评价，默认好评';
              }
              $comment_data=[
                  'goods_id'  =>$value['goods_id'],
                  'user_id'   =>$orderInfo['user_id'],
                  'order_id'  =>$order_id,
              ];
              $comment_data['content']=$value['content'];
              $comment_data['star_num']=$value['star_num'];
              $comment_data['add_time']=time();
              $res = $this->comment->insertGetId($comment_data);
              if(!empty($value['images'])){
                  for($i=0;$i<count($value['images']);$i++){
                      $image_data=[
                          'comment_id' =>$res,
                          'img_path'   =>$value['images'][$i],
                          'add_time'   =>time()
                      ];
                      $this->comment_image->insertGetId($image_data);
                  }
              }
              $this->orderGoods->save(['is_comment'=>1],['order_id'=>$order_id]);
          }
          $this->comment->commit();
          $msg['message']=checkMsg(COMMENT_SUCCESS);
      }catch (Exception $e){
         $this->comment->rollback();
          $msg['message']=checkMsg(COMMENT_FAIL);
      }
    return $msg;
  }

}